package controller;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Duang;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheInterceptor;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.CacheName;
import com.jfinal.plugin.ehcache.EvictInterceptor;
import com.jfinal.plugin.redis.Cache;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.upload.UploadFile;
import config.interceptor.DemoInterceptor;
import config.interceptor.InjectInterceptor;
import config.interceptor.MethodInterceptor;
import model.User;
import service.OrderService;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;

/**
 * Created by Administrator on 2016/12/29.
 */
@Before(DemoInterceptor.class)
public class UserController extends Controller{
    @Before(MethodInterceptor.class)
    public void backJSON(){
        System.out.println("backjson");
        setAttr("name","朱乾力");
        setAttr("age",123);
        setAttr("message","sadsa1123");
        setAttr("名字","adsd");
        List list = new ArrayList<User>();
        for(int i=0;i<1;i++) {
            User user = new User().set("acc_username", "James").set("acc_userid", 25).set("acc_password", "asda")
                    .set("acc_roleid", 1);
            list.add(user);
        }
        renderJson("users",list);

        renderJson(new String[]{"name","名字","sdsa"});

        renderFile(new File("C:\\Users\\Administrator\\Desktop\\app.groovy"));
        renderFile("hello.groovy");
    }
    @Before(MethodInterceptor.class)
    public void toservice(){
        OrderService service = Duang.duang(OrderService.class, InjectInterceptor.class);
        service.payment(1,1);
        service.getone();

        renderNull();
    }

    @Clear
    public void testDb(){
        System.out.println("testDb");

        boolean success = Db.use("mysql").tx(new IAtom() {

            public boolean run() throws SQLException {
                int count2 = 0;
                int count1 = 0;
                try {
                    count2 = Db.use("mysql").update("update account set cash = cash + ? where id = ?", 700, 2);
                    count1 = Db.use("mysql").update("update account set cash = cash - ? where id = ?", 700, 1);
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
                return count2==1&&count1==1;
            }
        });

        System.out.println(success);


        renderNull();
    }



    @Clear
    public void toHtml(){
        render("/html/saveuser.html");


    }

    public void toJsp(){
        renderJsp("/jsp/test.jsp");
    }


    public void savefile(){
        UploadFile file = getFile("file");
        if(file == null){
            renderText("savefile fail");
            return;
        }
        String contentType = file.getContentType();
        String fileName = file.getFileName();
        String originalFileName = file.getOriginalFileName();
        String parameterName = file.getParameterName();
        String uploadPath = file.getUploadPath();

        System.out.println("contentType: "+contentType);
        System.out.println("fileName: "+fileName);
        System.out.println("originalFileName: "+originalFileName);
        System.out.println("paramentName: "+parameterName);
        System.out.println("uploadPath: "+uploadPath);

        File file1 = file.getFile();

        renderText("savefile success!");
    }


    public void save() throws UnsupportedEncodingException {
        User user = getModel(User.class);

        /*User user = new User().set("acc_username", "James").set("acc_userid", 25).set("acc_password", "asda")
                .set("acc_roleid", 1);
        user.save();*/

        String zhongwen = getPara(5);
        System.out.println(URLDecoder.decode(getPara(5),"UTF-8"));
        System.out.println("get传参"+getPara("zhongwen"));

        System.out.println(new String(getPara(5).toString().getBytes("ISO-8859-1"), "utf-8"));

        System.out.println(getParaToInt(0)+" "+ getPara(1)+" "+getPara(5));
        System.out.println(getPara());


        System.out.println("---------------------");
        System.out.println("测试getParaNames");
        Enumeration<String> paraNames = getParaNames();
        while(paraNames.hasMoreElements())
            System.out.println(paraNames.nextElement());
        System.out.println("--------------------");

        System.out.println("----------------------");
        System.out.println("测试getPataMap");
        Map<String, String[]> paraMap = getParaMap();
        Set<String> keys = paraMap.keySet();
        for(String key : keys){
            String[] values = paraMap.get(key);
            System.out.print(key+":");
            for(String value : values)
                System.out.print(value);
            System.out.println();
        }
        System.out.println("--------------------------");
        String[] values = getParaMap().get("testGetPara");
        /*String[] values = getRequest().getParameterValues("testGetPara");*/
        System.out.println(getRequest().getParameterValues("testGetPara")[1]);
        renderText("usercontroller "+user.getStr("acc_password")+getPara(5));
    }


    /**
     * 测试缓存插件
     */
    @Clear
    @Before(CacheInterceptor.class)
    @CacheName("newslist")
    public void list(){
        List<Record> bloglist = Db.use("mysql").find("select * from blog");
        Record account = Db.use("mysql").findById("account",2);
        setAttr("bloglist", bloglist);
        setAttr("account", account);
        int i =0;
        for(Record record : bloglist){
            CacheKit.put("newslist","blog"+i,record);
            /*Cache newslist = CacheKit.getCacheManager().getCache("newslist");
            newslist.put(new Element("blog"+i,record));
            newslist.flush();*/

            i++;


        }


        render("/html/show.html");
    }
    @Clear
    public void selectlist(){
        for(int i=0;i<10;i++){
            System.out.println(CacheKit.get("newslist","blog"+i));

        }
        List newslist = CacheKit.getKeys("newslist");
        for(Object keyname : newslist){
            System.out.println(keyname);
        }
        System.out.println(CacheKit.get("newslist","/user213/list"));
        System.out.println(CacheKit.get("newslist","account"));
        renderNull();
    }
    @Clear
    @Before(EvictInterceptor.class)
    @CacheName("newslist")
    public void clearCache(){

        LinkedHashMap map = new LinkedHashMap();

        renderNull();
    }

    public void shutdown(){
        CacheKit.getCacheManager().shutdown();
        renderNull();
    }

    @Clear
    public void testRedis(){
        Cache news = Redis.use("news");
        news.set("news1","akldasjdaldad");
        news.set("news2","2222222222222222");
        Cache bbs = Redis.use("bbs");
        bbs.set("bbs1","bbs1");
        bbs.set("bbs2","bbbbbbbbbbbbbbb俺家里打");



        Redis.use().set("newsorbbs","哪个");



        System.out.println(bbs.get("bbs1")+" "+bbs.get("bbs2"));
        System.out.println(news.get("news1")+" "+news.get("news2"));
        //redis是同一个  所以都能有值
        System.out.println(bbs.get("newsorbbs")+" "+news.get("newsorbbs"));
        System.out.println(bbs.get("news1"));

        System.out.println(bbs.get("sadsa"));
        renderNull();
    }



}
